import React,{Component} from 'react';
import '../../style/admin_less/broad.less';
import $ from 'jquery'
import moment from 'moment';
import Pages from '../Pages'
import {Urls} from '../../config/urls'
import { Spin,message,DatePicker} from 'antd';
import * as pub from '../../config/public';
import Dropzone from 'react-dropzone'
import Layer from '../Layer'
import sfetch from 'sfetch'

//新增模块儿
class AddBroad extends Component {
	constructor(props) {
		super(props)
		this.state = {
			cover_image:[],
			is_choose_image:false,
			liveStats:'A',
			liveTitle:this.props.liveTitle?this.props.liveTitle:'',
			liveStartTime:this.props.liveStartTime?this.props.liveStatrtTime:'',
			liveEndTime:this.props.liveEndTime?this.props.liveEndTime:'',
			liveInfoDesc:this.props.liveInfoDesc?this.props.liveInfoDesc:'',
			mainId:this.props.mainId?this.props.mainId:'',
			loading:false
		}
	}
	componentWillReceiveProps(nextProps) {
		let sD = new Date(nextProps.liveStartTime)
		let startTime=sD.getFullYear() + '/' + (sD.getMonth() + 1>9?sD.getMonth() + 1:'0'+(sD.getMonth() + 1)) + '/' + (sD.getDate()>9?sD.getDate():'0'+sD.getDate()) + ' ' + (sD.getHours()>9?sD.getHours():'0'+sD.getHours()) + ':' + (sD.getMinutes()>9?sD.getMinutes():'0'+sD.getMinutes()) + ':' + (sD.getSeconds()>9?sD.getSeconds():'0'+sD.getSeconds())
 		let eD = new Date(nextProps.liveEndTime)
 		let endTime=eD.getFullYear() + '/' + (eD.getMonth() + 1>9?eD.getMonth() + 1:'0'+(eD.getMonth() + 1)) + '/' + (eD.getDate()>9?eD.getDate():'0'+eD.getDate()) + ' ' + (eD.getHours()>9?eD.getHours():'0'+eD.getHours()) + ':' + (eD.getMinutes()>9?eD.getMinutes():'0'+eD.getMinutes()) + ':' + (eD.getSeconds()>9?eD.getSeconds():'0'+eD.getSeconds())
		this.setState({
			LayerTitle:nextProps.LayerTitle,
			visible: nextProps.modalshow,
			mainId: nextProps.mainId?nextProps.mainId:'',
			liveTitle: nextProps.liveTitle,
			liveStartTime: startTime,
			liveEndTime:endTime,
			liveInfoDesc:nextProps.liveInfoDesc ,
			livePath:nextProps.livePath ,
			liveStats:nextProps.liveStats ,
			beginDate:moment(new Date(nextProps.liveStartTime?nextProps.liveStartTime:(new Date())), 'YYYY/MM/DD HH:mm:ss'),
			endDate:moment(new Date(nextProps.liveEndTime?nextProps.liveEndTime:(new Date())), 'YYYY/MM/DD HH:mm:ss ')
		});
    }
	addNew(){
		this.setState({
			beginDate:moment(new Date(new Date()),'YYYY/MM/DD HH:mm:ss'),
			endDate:moment(new Date(new Date()),'YYYY/MM/DD HH:mm:ss'),
		})
		
	}
	showModal = () => {
		this.addNew()
		this.setState({
			visible: true,
			LayerTitle:'新增直播',
			liveStats:'A',
			liveTitle:'',
			liveStartTime:this.state.beginDate.format('YYYY/MM/DD HH:mm:ss'),
			liveEndTime:this.state.endDate.format('YYYY/MM/DD HH:mm:ss'),
			liveInfoDesc:'',
			file:'',
			mainId:'',
			cover_image:[],
			livePath:''
		});
	}
	hideMdoal = (e) => {
		this.props.modalhidden()
		this.setState({
			visible: false,
			liveTitle:'',
			liveStartTime:'',
			liveEndTime:'',
			liveInfoDesc:'',
			file:'',
			mainId:'',
			cover_image:[],
			livePath:'',
			loading:false
		});
	}
	liveTitle=()=>{
		this.setState({liveTitle:this.refs.liveTitle.value.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'')})
	}
	liveInfoDesc=()=>{
		this.setState({liveInfoDesc:this.refs.liveInfoDesc.value.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'')})
	}
	startChange(date, dateString) {
     this.setState({
		 liveStartTime:date.format('YYYY/MM/DD HH:mm:ss')
	 }) 
    }  
	endChange(date,dateString) {
      this.setState({
		  liveEndTime:date.format('YYYY/MM/DD HH:mm:ss')
	  })
	}
	onSubmit(e){
		e.preventDefault();
		pub.loading(this,true);
		let sNewDate=new Date();
   			sNewDate = sNewDate.getTime();
		let sLiveStartTime=this.state.liveStartTime;
   			sLiveStartTime = new Date(Date.parse(sLiveStartTime.replace(/-/g, "/")));
   			sLiveStartTime = sLiveStartTime.getTime();
		let sLiveEndTime  = this.state.liveEndTime;
			sLiveEndTime  = new Date(Date.parse(sLiveEndTime.replace(/-/g, "/")));
			sLiveEndTime  = sLiveEndTime.getTime();
		if(sLiveStartTime<sNewDate){
			message.error('开始时间不能小于当前时间',3);
			pub.loading(this,false);
			return
		}
		if(sLiveStartTime>sLiveEndTime){
			message.error('结束时间不能小于开始时间',3);
			pub.loading(this,false);
			return
		}
		let str1 = this.refs.liveTitle.value
		let str2 = this.state.liveStartTime
		let str3 = this.state.liveEndTime
		let str4 = this.refs.liveInfoDesc.value	
		let str5 = this.state.mainId?this.state.mainId:''
		let formData = new FormData();
			formData.append('liveStats',this.state.liveStats?this.state.liveStats:'A');
			formData.append('liveTitle',str1);
			formData.append('liveStartTime',str2);
			formData.append('liveEndTime',str3);
			formData.append('liveInfoDesc',str4);
			formData.append('mainId',str5);
			/*formData.append('file',this.state.cover_image);*/
			 if(this.state.livePath===''){
		        formData.append('file',this.state.cover_image);
		     }else{
		        formData.append('file',this.state.livePath);
		     }
		let url = pub.url_format(Urls.IUDLIVEINFO,'iudLiveInfo','button')
		sfetch.post({
      		url: url,
     		body: formData,
      		dataType: 'formdata'
  }).then((data) => {
    	if(data.json.result==='RC100'){
    		this.props.show()
    		this.setState({
				liveTitle:'',
    			liveStartTime:'',
    			liveEndTime:'',
    			liveInfoDesc:'',
    			mainId:'',
    			file:'',
    			cover_image:[],
    			livePath:''
    		})
    	}
     	else {
       	 	message.error(data.json.errMsg,3);
      	}
		  pub.loading(this,false);
    });
	    this.setState({
			modalshow: false,
			loading:false
		});
	}
	chooseImage(accepted, rejected){
		this.setState({
			cover_image:accepted[0],
			is_choose_image:true,
			livePath:''
		})
	}
	render(){
		return(
	    <div>
			<Layer
				title = {this.state.LayerTitle}
				show={this.state.visible}
				hide={(e)=>this.hideMdoal(e)}
				width="636px"
				height="450px"
			>
			    <Spin spinning={this.state.loading}>
					<form className="layui-layer-content" onSubmit={(e)=>this.onSubmit(e)}>
						<div className="row">
							<div className="pop-box-1">
								<div className="book-add clearFix">
								{
									this.state.livePath!==''?
									<img src={pub.getFile(this.state.livePath)} alt='封面图片' />
									:
									<img src={this.state.cover_image.preview} alt='封面图片' />
								}
									<ul className="book-info">
										<li><label><span>*</span>直播名称：</label><input type="text" required="required" value={this.state.liveTitle} onChange={this.liveTitle.bind()} ref="liveTitle" /></li>
										<li>
											<label><span>*</span>开始时间：</label>{/*<input type="text" value={this.state.liveStartTime} onChange={this.liveStartTime.bind()} ref="liveStartTime"/>*/}
											<DatePicker onChange={this.startChange.bind(this)} required="required"  showTime format="YYYY/MM/DD HH:mm:ss" defaultValue={this.state.beginDate}/>
										</li>
										<li>
											<label><span>*</span>结束时间：</label>{/*<input type="text" value={this.state.liveEndTime} onChange={this.liveEndTime.bind()} ref="liveEndTime"/>*/}
											<DatePicker onChange={this.endChange.bind(this)} defaultValue={this.state.endDate} showTime format="YYYY/MM/DD HH:mm:ss"/>
										</li>
										<li><label><span>*</span>内容描述：</label><textarea required="required" value={this.state.liveInfoDesc} onChange={this.liveInfoDesc.bind()} ref="liveInfoDesc"></textarea></li>
									</ul>
									<Dropzone
										// maxSize= {31457280}
										multiple={false}
										onDrop={this.chooseImage.bind(this)}
										className = 'choose-image'
										accept="image/jpeg, image/png"
									>
										<label className="file">上传封面</label>

									</Dropzone>

								</div>
							</div>
							<div className="pop-btn">
								<a className="btn btn-grey layui-layer-close" onClick={(e)=>this.hideMdoal(e)}>取消</a>
								<button type="submit" className="btn add-book" >确定</button>
							</div>
						</div>
					</form>		
					</Spin>
			</Layer>	
		    <a className="btn btn-blue" onClick={(e)=>this.showModal(e)}>新增</a>
		</div>
		)
	}
}
class BroadManagement extends Component {
	constructor(args) {
		super()
		this.state = {
			loading:false,
			activeIndex : 0,
			jumpPage:1,
			liveInfolist:[],
			mainId:'',
			liveStats:'',
			totalPage:'',
		}		
	}
	show(){
		this.setState({loading: true});
		let _this = this
		let data = pub.behavior({
				pageno:this.state.jumpPage
			},'selectLiveInfoList','button')
		$.ajax({
			url:Urls.LIVEMANAGEMENT,
			data:data,
			success:function(data){
					_this.setState({totalPage:data.total})
					_this.setState({liveInfolist:data.liveInfoList?data.liveInfoList:[]})
					_this.setState({loading: false});
					
			},
			error:function(data){
				message.error('请求失败',3);
				_this.setState({loading: false});
			}
		})
		this.setState({modalshow:false})
	}
	componentWillMount(){
		this.show()
	}
	del(item,index) {
		item.liveStats = "D"
		let _this =this
		this.setState({
			mainId:item.mainId,
			liveStats:item.liveStats,
			totalPage:item.total
		})
		let data = pub.behavior({
				mainId:item.mainId,liveStats:'D'
			},'iudLiveInfo','button')
		$.ajax({
			type:"POST",
			url:Urls.IUDLIVEINFO,
			data:data,
			success:function(data){
				let odata = pub.behavior({
						pageno:_this.state.jumpPage
					},'selectLiveInfoList','button')
				$.ajax({
					url:Urls.LIVEMANAGEMENT,
					data:odata,
					success:function(data){
						_this.setState({totalPage:data.total})
						_this.setState({liveInfolist:data.liveInfoList})
					}
				})
			},
			error:function(data){
				message.error('请求失败',3);
			}
		})
	}
	searchinglist(){
		/*console.log(this.refs.searchModel.value)*/
		let _this = this
		/*console.log(_this.refs.searchModel.value)*/
		let data = pub.behavior({
				search:_this.refs.searchModel.value
			},'selectLiveInfoList','button')
		$.ajax({
			url:Urls.LIVEMANAGEMENT,
			data:data,
			success:function(data){
				_this.setState({liveInfolist:data.liveInfoList?data.liveInfoList:[]})
				_this.setState({totalPage:data.total})
			},
			error:function(data){
				message.error('请求失败',3);
			}
		})
	}
	
	edit(item,index){
	 	let str0 = item.mainId
		let formData = new FormData();
			formData.append('mainId',str0);
		let url = pub.url_format(Urls.SELECTLIVEINFO,'selectLiveInfo','button')
		sfetch.post({
      		url: url,
     		body: formData,
      		dataType: 'formdata'
    }).then((data) => {
    		this.setState({
    			modalshow:true,
    			liveTitle:data.json.liveinformation.liveTitle,
				liveStartTime:data.json.liveinformation.liveStartTime,
				liveEndTime:data.json.liveinformation.liveEndTime,
				liveInfoDesc:data.json.liveinformation.liveInfoDesc,
				livePath:data.json.liveinformation.livePath,
				liveStats:'U',
				mainId:data.json.liveinformation.mainId,
				LayerTitle:"编辑直播"
    		})
     		 if (data.ok) {
	     	 } else {
	       	message.error(data.errMsg,3);
	      	}
	    });
	}
	jump(page){
		let _this = this
		this.setState({jumpPage:page})
		let data = pub.behavior({
				pageno:page
			},'selectLiveInfoList','button')
		$.ajax({
			url:Urls.LIVEMANAGEMENT,
			data:data,
			success:function(data){
				_this.setState({liveInfolist:data.liveInfoList})
				_this.setState({modalshow:false})
			},
			error:function(data){
				message.error('请求失败',3);
			}
		})
	}
	modalhidden(){
		this.setState({
			modalshow:false
		})
	}
	numberInputs=(e)=>{
		let value=e.target.value;
		e.target.value=value.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'');
	}
	render() {
		return (
			<div className="container broad">
				<div className="common-title">直播管理
					<div className="filter-search floatR">
						<input type="text" placeholder="搜索" ref="searchModel" onKeyUp={this.numberInputs}/>
						<a className="btn search-btn" onClick={()=>this.searchinglist()}><i className="icon-search" ></i></a>
					</div>
				</div>
				<div className="row select-filter clearFix">
					
					 <AddBroad liveStats={this.state.liveStats} show={this.show.bind(this)} modalhidden={this.modalhidden.bind(this)} modalshow={this.state.modalshow} liveStartTime={this.state.liveStartTime} liveEndTime={this.state.liveEndTime} liveTitle={this.state.liveTitle} liveInfoDesc={this.state.liveInfoDesc} livePath={this.state.livePath} mainId={this.state.mainId} LayerTitle={this.state.LayerTitle}/>
				</div>

				<div className="row">
					<Spin spinning={this.state.loading} tip="加载列表中...">
					<ul className="live-list clearFix">
						{
							this.state.liveInfolist.map((item,index)=>{
							
								let title     = item.liveTitle.split(',')[0]
								let sD        = new Date(item.liveStartTime);
								let startTime = sD.getFullYear() + '.' + (sD.getMonth() + 1>9?sD.getMonth() + 1:'0'+(sD.getMonth() + 1)) + '.' + (sD.getDate()>9?sD.getDate():'0'+sD.getDate()) + ' ' + (sD.getHours()>9?sD.getHours():'0'+sD.getHours()) + ':' + (sD.getMinutes()>9?sD.getMinutes():'0'+sD.getMinutes())
								let eD        =  new Date(item.liveEndTime)
								let endTime   = eD.getFullYear() + '.' + (eD.getMonth() + 1>9?eD.getMonth() + 1:'0'+(eD.getMonth() + 1)) + '.' + (eD.getDate()>9?eD.getDate():'0'+eD.getDate()) + ' ' + (eD.getHours()>9?eD.getHours():'0'+eD.getHours()) + ':' + (eD.getMinutes()>9?eD.getMinutes():'0'+eD.getMinutes())
								return(
									<li key={index} style={{display:item.liveStats==='D'?'none':'block'}}>
										<img src={pub.getFile(item.livePath)} alt='test' />
										<div className="book-details">
											<p>{title}</p>
											<p>开始时间:{startTime}</p>
											<p>结束时间:{endTime}</p>
											<div className="edit-download">
										{/*<Edit mainId={item.mainId} startTime={item.liveStartTime} endTime={item.liveEndTime} title={title} liveInfoDesc={item.liveInfoDesc} picPath={item.livePath}/>*/}
												<a onClick={()=>this.edit(item,index)}>编辑</a>
												<a className="red" onClick={()=>this.del(item,index)}>下架</a>
											</div>
										</div>
									</li>
								)
							})
						}
					</ul>
					</Spin>
				</div>
				<div className="line"></div>
				<Pages totalPage={this.state.totalPage} jump={this.jump.bind(this)}/>
			</div>

		)
	}

}
export default BroadManagement